// pages/studyPlan/studyPlan.js
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    days: [],
    questions: [],
    day: 1,
    que: 10,
    daykey: 1,
    quekey: 1,
    dayflag: 1,
    queflag: 2,
    nowflag: 0,
    paperList: [],
    tempCourse: null, // 用户添加的课程，没有选择时间和题目个数的时候 通过缓存得到
    currentCourse: {}, // 用户当前选定的课程
    isGoingCourse: {}, // 正在进行的课程
    isChangePlan: false //判断是否是修改计划
  },
  onMytouchEvent(e) {
    let flag = e.detail.flag
    let selectedKey = e.detail.selectKey
    let tempque = this.data.que
    let tempday = this.data.day
    if (flag === 1) {
      tempday = this.data.days[selectedKey]
      tempque = Math.ceil(this.data.currentCourse.subjectCount / tempday / 10) * 10
    }
    if (flag === 2) {
      tempque = this.data.questions[selectedKey]
      tempday = Math.ceil(this.data.currentCourse.subjectCount / tempque)
    }
    let daykey = this.data.days.findIndex((v) => { return v === tempday })
    let quekey = this.data.questions.findIndex((v) => { return v === tempque })
    this.setData({
      nowflag: flag,
      day: tempday,
      que: tempque,
      daykey: daykey,
      quekey: quekey
    })
    // console.log(flag, this.data.daykey, this.data.quekey)
  },
  addPlan () {
    if (!this.data.tempCourse) {
      // 不是通过新增计划返回的
      if(this.data.paperList.length > 0) {
        // 如果已经有正在学习的计划给出提示
        wx.showModal({
          title: '提示',
          content: '您有正在学习的计划，新增计划会覆盖旧计划哦',
          success: (res) => {
            if (res.confirm) {
              app.formDirectUrl('/pages/studyPlanAdd/studyPlanAdd')
            }
          }
        })
      }
      else {
        app.formDirectUrl('/pages/studyPlanAdd/studyPlanAdd')
      }
    }
    else {
      // 通过新增计划返回的
      wx.showModal({
        title: '提示',
        content: '您新增的计划还未保存，保存完才能继续新增计划！',
      })
    }
  },
  savePlan () {
    // 保存设定计划 (天数，正在学习的课程Id, 题个数)
    if (this.data.tempCourse || this.data.isChangePlan) {
      let param = { day: this.data.day, number: this.data.que, courseId: this.data.currentCourse.courseId }
      app.requestModule('/app/plan/setStudyPlan', param, this.savePlanCallback, this.savePlanFailCallback, 'POST')
    }
    else {
      wx.showModal({
        title: '提示',
        content: '计划正在进行不能进行修改！',
      })
    }
  },
  savePlanCallback (res) {
    this.setData({
      isChangePlan: false
    })
    app.removeQAListStorage()
    wx.showModal({
      title: '提示',
      content: '保存成功，您可以开始新计划的学习！',
      success: (res) => {
        if(res.confirm) {
          app.formDirectUrl('/pages/home/home')
        }
      }
    })
  },
  savePlanFailCallback (res) {
    // app.formDirectUrl('/pages/studyPlanAdd/studyPlanAdd')
  },
  getPlist () {
    app.requestModule('/app/plan/getAllPlanInfo', {}, this.getPlistCallback, () => { }, 'GET')
  },
  getPlistCallback (res) {
    let plist = []
    if (res.data && res.data.length > 0) {
     plist = res.data
     plist.map((v, k) => {
       if (parseInt(v.state) === 1 || parseInt(v.state) === 0) {
         v.active = 'active'
         this.setData({
           isGoingCourse: v
         })
       }
       else {
         v.active = ''
       }
     })
    }
    // console.log(plist)
    this.setData({
      paperList: plist
    })
    // 根据courseplan 判断 用户是从新增进来还是从 我的计划列表进来
    // 从而设定学习天数和学习题数
    let courseplan = wx.getStorageSync('courseplan') || null
    if (courseplan) {
      let tempCourse = JSON.parse(courseplan)
      let configcoung = app.globalData.systemConfig ? parseInt(app.globalData.systemConfig[0].name) : 10
      this.setData({
        tempCourse: tempCourse
      })
      this.setList(tempCourse, configcoung)
    }
    else {
      // 获取当前学习计划
      app.requestModule('/app/plan/getStudyPlan', {}, this.getStudyPlanCallback, () => { }, 'GET')
    }
  },
  getStudyPlanCallback (res) {
    if (res.data) {
      this.setList(res.data, res.data.everydayCount, res.data.subjectCount / res.data.everydayCount)
    }
  },
  setList(currentCourse, configcoung, day) {
    //初始化设定天数题目数正在学习的课程
    let questions = []
    let days = []
    let count = currentCourse.subjectCount
    for (let i = 10; i <= count; i += 10) {
      questions.push(i)
      let countday = Math.ceil(count / i)
      if (!days.includes(countday)) {
        days.push(countday)
      }
    }
   
    this.setData({
      currentCourse: currentCourse,
      day: Math.ceil(count / configcoung),
      que: configcoung,
      days: days,
      questions: questions
    })
    // 初始化设置学习周期
    this.setScrollCycle()
    // console.log(days, questions, this.data.day, this.data.que)
  },
  setScrollCycle (){
    // console.log(this.data.day, this.data.que)
    let daykey = this.data.days.findIndex((v) => { return v === this.data.day })
    let quekey = this.data.questions.findIndex((v) => { return v === this.data.que })
    this.setData({
      nowflag: 3,
      daykey: daykey,
      quekey: quekey
    })
  },
  changePlan (e) {
    if (!this.data.tempCourse) {
      var plan = e.currentTarget.dataset.item
      //如果点击的不是正在学习中的课程
      console.log(this.data.isGoingCourse, plan)
      if (parseInt(plan.courseId) !== parseInt(this.data.isGoingCourse.courseId)) {
        let configcoung = app.globalData.systemConfig ? parseInt(app.globalData.systemConfig[0].name) : 10
        this.setList(plan, configcoung)
        this.data.paperList.map((v, k) => {
          console.log(v.courseId, plan.courseId)
          if (parseInt(v.courseId) === parseInt(plan.courseId)) {
            v.active = 'temp'
          }
        }) 
        this.setData({
          paperList: this.data.paperList,
          isChangePlan: true
        })
      }
      else {
        wx.showModal({
          title: '提示',
          content: '不能修改正在学习的计划！',
        })
      }
    }
    else {
      wx.showModal({
        title: '提示',
        content: '您有正在添加的计划，不能修改计划！',
      })
    }
  },
  deletePlan (e) {
    var deleteplan = e.currentTarget.dataset.item
    this.deletePlanId = deleteplan.planId
    wx.showModal({
      title: '提示',
      content: '是否要删除该计划？',
      success: (res) => {
        if(res.confirm) {
          // 执行删除计划
          let param = { planId: this.deletePlanId}
          app.requestModule('/app/plan/deleteStudyPlan', param, this.deletePlanCallback, () => { }, 'POST')
        }
      }
    })
    // console.log(deleteplan)
  },
  deletePlanCallback (res) {
    wx.showModal({
      title: '提示',
      content: '删除成功',
      success: () => {
        let plist = this.data.paperList
        for (let i = 0; i < plist.length; i++) {
          if (plist[i].planId === this.deletePlanId) {
            plist.splice(i, 1)
            break; 
          }
        }
        this.setData({
          paperList: plist
        })
        console.log(plist)
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 获取试卷列表
    this.getPlist()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    // 离开页面就不存在修改计划了，如果用户点击进行修改计划但是又不保存， 那么在他离开页面的时候必须置为false
    this.setData({
      isChangePlan: false
    })
    wx.removeStorage({
      key: 'courseplan',
      success: function (res) {
        console.log('remove')
      },
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  }
})